﻿using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace DimensionsHelper.LanguageService.Syntax;

public class IntegerLiteral : Literal<int>
{
    internal IntegerLiteral(SyntaxNode? parent) :
        base(SyntaxKinds.Integer, 0, parent)
    {
    }


    /// <summary>
    ///     默认的空整数常量
    /// </summary>
    public static IntegerLiteral Default { get; } = new(null);


    /// <summary>
    ///     判断整数常量是否是默认值。
    /// </summary>
    public static bool IsEmptyOrDefault([NotNullWhen(false)] IntegerLiteral? literal)
    {
        return literal == null || ReferenceEquals(literal, Default);
    }
}


public static partial class NodeFactory
{
    public static IntegerLiteral CreateIntegerLiteral(SyntaxNode? parent, int value)
    {
        return new IntegerLiteral(parent) { Value = value };
    }


    public static IntegerLiteral CreateIntegerLiteral(SourceNode source)
    {
        Debug.Assert(source.IsNode(SyntaxKinds.Integer));
        IntegerLiteral literal = CreateIntegerLiteral(null, (int)source.TokenNumberValue);
        literal.UpdateFrom(source);
        return literal;
    }
}


public static partial class NodeConverter
{
    public static bool TryConvertNegativeInteger(Expression expression,
        [MaybeNullWhen(false)] out IntegerLiteral integerLiteral)
    {
        integerLiteral = null;

        if (expression.Is<UnaryExpression>(SyntaxKinds.UnaryExpression, out UnaryExpression? unary) &&
            unary.Operator.IsNode(SyntaxKinds.MinusToken) &&
            unary.Expression.Is<IntegerLiteral>(SyntaxKinds.Integer, out IntegerLiteral? sourceInteger))
        {
            integerLiteral = NodeFactory.CreateIntegerLiteral(null, -sourceInteger.Value);
            integerLiteral.UpdateFrom(expression);
            return true;
        }

        return false;
    }
}